﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Navigation;
using CuteRibs.MVVMLib;
using CuteRibs.WowArmory.Models;
using CuteRibs.WowArmory.Resources;

namespace CuteRibs.WowArmory.ViewModels
{
	public class RealmsPageViewModel : PageViewModelBase
	{
		public AppRes AppRes { get { return App.AppResource; } }

		private AppTitleControlViewModel appTitle;

		public AppTitleControlViewModel AppTitle
		{
			get { return this.appTitle; }
			set
			{
				if (this.appTitle != value)
				{
					this.appTitle = value;
					this.NotifyPropertyChanged("AppTitle");
				}
			}
		}

		private ObservableCollection<RealmViewModel> realms;

		public ObservableCollection<RealmViewModel> Realms
		{
			get { return this.realms; }
			set
			{
				if (this.realms != value)
				{
					this.realms = value;
					this.NotifyPropertyChanged("Realms");
				}
			}
		}

		public RealmsPageViewModel()
		{
			if (App.IsDesignMode)
			{
				this.SetRegion();
			}
		}

		public override void OnNavigatedTo(ViewBase sender, NavigationEventArgs eventArgs, NavigationContext context)
		{
			base.OnNavigatedTo(sender, eventArgs, context);

			this.SetRegion();
		}

		private void SetRegion()
		{
			var region = App.RegionData.Region;
			this.AppTitle = new AppTitleControlViewModel(AppRes.Title_Realms, region.DisplayName);
			this.GetRealms(region);
		}

		private void GetRealms(Region region)
		{
			this.Realms = new ObservableCollection<RealmViewModel>(App.RegionData.Realms.Select(r => new RealmViewModel(r)));
		}

		public void DeleteRealm(string slug)
		{
			this.BeginInvoke(delegate
			{
				var realm = App.RegionData.Realms.FirstOrDefault(r => r.Slug == slug);

				if (realm != null)
				{
					App.RegionData.Realms.Remove(realm);
					App.SaveMyData();
				}
			});
		}

		public void NavigateToSearchPage()
		{
			this.Frame.Navigate("/Views/RealmSearchPageView.xaml?Host={0}", App.RegionData.Region.Domain);
		}

		public void NavigateToDetailPage(string realmSlug)
		{
			this.Frame.Navigate("/Views/RealmDetailPageView.xaml?Host={0}&Realm={1}", App.RegionData.Region.Domain, realmSlug);
		}
	}
}
